package com.styytech.dadabao.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.RegistResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.Md5Utils;
import com.styytech.dadabao.utils.NumberUtil;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;

/**
 * 忘记密码界面
 */
@ContentView(R.layout.activity_reset_password)
public class ResetActivity extends BaseActivity implements View.OnClickListener {

    /**
     * 验证码
     */
    public final int REQUEST_CODE_AUTH_CODE = 1;
    /**
     * 重置密码
     */
    public final int REQUEST_CODE_RESET = 2;
    /**
     * 验证验证码
     */
    public final int REQUEST_CODE_CHECK_AUTH = 3;
    /**
     * 验证手机号是否已注册
     */
    public final int REQUEST_CODE_CHECK_PHONE = 4;

    @ViewInject(R.id.et_number)
    EditText et_number;// 手机号
    @ViewInject(R.id.et_password)
    EditText et_password;// 密码
    @ViewInject(R.id.et_passwordOk)
    EditText et_passwordOk;// 确认密码
    @ViewInject(R.id.et_auth_code)
    EditText et_auth_code;// 验证码
    @ViewInject(R.id.tv_auth_code)
    TextView tv_auth_code;// 发送验证码按钮
    @ViewInject(R.id.bt_ok)
    Button bt_ok;// 确定修改
    @ViewInject(R.id.bt_next)
    Button bt_next;// 下一步
    @ViewInject(R.id.llyt_auth_code)
    LinearLayout llyt_auth_code;// 获取验证码布局
    @ViewInject(R.id.llyt_passwdord)
    LinearLayout llyt_passwdord;// 重置密码布局
    /*上下文*/
    Context context;
    /*loading框*/
    CustomLoadingDialog mdlg;

    private String phoneNum = "";// 手机号
    private String auchuCode = "";// 验证码
    private String password = "";// 密码
    private String passwordOk = "";// 确认密码

    /**
     * 计时器
     */
    private TimeCount timeCount = null;
    /**
     * 0：还未计时
     * 1：正在计时：
     * -1：
     */
    private boolean isTimeCount = false;// false：还未计时或计时结束，true：正在计时
    private boolean isComplete = false;// false：还未符合完成的条件，true：已经符合

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        initView();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        DadaApplication.addActivity(this);
        setTopBar("忘记密码", View.VISIBLE);
        /*隐藏重置密码的布局*/
        llyt_auth_code.setVisibility(View.VISIBLE);
        llyt_passwdord.setVisibility(View.GONE);
        /*onclick事件绑定*/
        tv_auth_code.setOnClickListener(this);
        et_number.addTextChangedListener(phoneNumberEdit);
        et_auth_code.addTextChangedListener(authCodeEdit);
        et_password.addTextChangedListener(passwordEdit);
        et_passwordOk.addTextChangedListener(passwordEdit);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_auth_code:// 获取验证码
                checkPhoneRegisted();
                break;
            case R.id.bt_ok://确定修改
                resetOk();
                break;
            case R.id.bt_next://确定修改
                checkAuthCode();
                break;
        }
    }


    /**
     * 获取验证码
     */
    public void getAuthCode() {
        /*获取用户输入的手机号*/
        phoneNum = et_number.getText().toString().trim();
        /*手机号过滤*/
        if (phoneNum.isEmpty()) {
            //手机号码不能为空
            toast(getResources().getString(R.string.number_no_empty));
            return;
        } else if (NumberUtil.checkNumber(phoneNum).getType() == NumberUtil.PhoneType.INVALIDPHONE) {
            //请填写正确手机号码
            toast(getResources().getString(R.string.number_to_right));
            return;
        }
        /*如果未开始计时或者计时结束，才能再次获取验证码*/
        if (!isTimeCount) { // 发送
            // 显示对话框
            mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "获取验证码", true);
            mdlg.show();
            /*获取验证码的接口*/
            String url = ConstantsServerUrl.getCheckCode();
            /*设置参数*/
            RequestParams params = new RequestParams();
            params.put("mobileNumber", phoneNum);
            /*验证码请求*/
            requestAuthCode(REQUEST_CODE_AUTH_CODE, url, params);
        } else {
            //短信已发送
            CommonUtils.showToastMsg(context, "" + getResources().getString(R.string.sms_had_sent));
        }
    }

    /**
     * 验证验证码
     */
    public void checkAuthCode() {
        /*获取手机号*/
        phoneNum = et_number.getText().toString().trim();
        auchuCode = et_auth_code.getText().toString().trim();
        /*对验证码异常过滤*/
        if (auchuCode.isEmpty()) {
            //验证码不能为空
            toast(getResources().getString(R.string.code_no_empty));
            return;
        } else if (auchuCode.length() != 6) {
            //验证码长度为6位
            toast(getResources().getString(R.string.code_must_six));
            return;
        }
        // 显示对话框
        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "", true);
        mdlg.setMessage("正在验证...");
        mdlg.show();
        /*获取验证验证码接口*/
        String url = ConstantsServerUrl.getValidateCheckCode();
        /*设置参数*/
        RequestParams params = new RequestParams();
        params.put("mobileNumber", phoneNum);
        params.put("checkCode", et_auth_code.getText().toString().trim());
        /*请求校验验证码*/
        requestAuthCode(REQUEST_CODE_CHECK_AUTH, url, params);
    }

    /**
     * 验证手机号是否已注册
     */
    public void checkPhoneRegisted() {
        /*获取手机号*/
        phoneNum = et_number.getText().toString().trim();
        /*对验证码异常过滤*/
        if (phoneNum.isEmpty()) {
            //验证码不能为空
            toast(getResources().getString(R.string.number_no_empty));
            return;
        } else if (NumberUtil.checkNumber(phoneNum).getType() == NumberUtil.PhoneType.INVALIDPHONE) {
            //验证码长度为6位
            toast(getResources().getString(R.string.number_to_right));
            return;
        }
        // 显示对话框
//        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "", true);
//        mdlg.setMessage("正在验证...");
//        mdlg.show();
        /*验证手机号是否已注册接口*/
        String url = ConstantsServerUrl.getCheckUserCdUrl();
        /*设置参数*/
        RequestParams params = new RequestParams();
        params.put("mobile", phoneNum);
        /*请求校验验证码*/
        requestAuthCode(REQUEST_CODE_CHECK_PHONE, url, params);
    }

    /**
     * 确认修改
     */
    private void resetOk() {

        phoneNum = et_number.getText().toString().trim();
        password = et_password.getText().toString().trim();
        passwordOk = et_passwordOk.getText().toString().trim();
        if (phoneNum.isEmpty()) {
            //手机号码不能为空
            toast(getResources().getString(R.string.number_no_empty));
            return;
        } else if (NumberUtil.checkNumber(phoneNum).getType() == NumberUtil.PhoneType.INVALIDPHONE) {
            //请填写正确手机号码
            toast(getResources().getString(R.string.number_to_right));
            return;
        } else if (password.isEmpty()) {
            //密码不能为空
            toast(getResources().getString(R.string.pwd_no_empty));
            return;
        } else if (password.length() < 6) {
            //密码不能少于6位
            toast(getResources().getString(R.string.pwd_too_low));
            return;
        } else if (password.length() > 30) {
            //密码长度不能大于18位
            toast(getResources().getString(R.string.pwd_too_much));
            return;
        } else if (passwordOk.isEmpty()) {
            //确定密码不能为空
            toast(getResources().getString(R.string.pwd_ensure_no_empty));
            return;
        } else if (!passwordOk.equals(password)) {
            //两次密码不一致
            toast(getResources().getString(R.string.pwd_no_agree));
            return;
        }
        // 重置密码请求
        resetRquest();

    }

    /**
     * 确认修改请求
     */
    private void resetRquest() {
        // 显示对话框
        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "重置密码", true);
        mdlg.show();

        String url = ConstantsServerUrl.getResetUserPasswordUrl();
        RequestParams params = new RequestParams();

        String mD5Pass = Md5Utils.hash(password);
        params.put("mobile", phoneNum);
        params.put("password", mD5Pass);

        requestAuthCode(REQUEST_CODE_RESET, url, params);
    }

    /**
     * 请求校验验证码
     *
     * @param rquestCode 请求码
     * @param url        请求的url接口
     * @param params     请求的参数
     */
    public void requestAuthCode(int rquestCode, String url, RequestParams params) {
        if (phoneNum.isEmpty()) {
            //手机号码不能为空
            CommonUtils.showToastMsg(context, getResources().getString(R.string.number_no_empty));
            return;
        }
        //获取验证码
        RegistResult requestResult = new RegistResult(rquestCode, responseResult);
        try {
            new HttpRequest(this).doPost(requestResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }


    /**
     * 注册请求结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            CommonUtils.closeDialog(mdlg);
            switch ((int) object) {
                case REQUEST_CODE_AUTH_CODE:
                    //获取验证码成功之后
                     /*开始计时*/
                    timeCount = new TimeCount(60000, 1000);
                    timeCount.start();
                    break;
                case REQUEST_CODE_RESET://重置密码请求
                    CommonUtils.showToastMsg(context, "重置成功！");
                    startMainActivity(LoginActivity.class);
                    break;
                case REQUEST_CODE_CHECK_AUTH://验证成功
                    isComplete = false;
                    llyt_auth_code.setVisibility(View.GONE);
                    llyt_passwdord.setVisibility(View.VISIBLE);
                case REQUEST_CODE_CHECK_PHONE://验证手机号是否已注册
                    getAuthCode();
                    break;
            }

        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.closeDialog(mdlg);
            CommonUtils.showToastMsg(context, "" + message);
        }
    };

    /**
     * 启动界面
     *
     * @param cls 需要启动的界面类
     */
    private void startMainActivity(Class<?> cls) {
        Intent intent = new Intent(context, cls);
        startActivity(intent);
        finish();
    }

    /**
     * 提示消息
     *
     * @param str 需要提示的消息
     */
    private void toast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }

    /**
     * 倒计时
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        /**
         * 计时完毕时触发
         */
        @Override
        public void onFinish() {
            isTimeCount = false;
            tv_auth_code.setText("重新发送");
//            tv_auth_code.setClickable(true);
            tv_auth_code.setTextColor(getResources().getColor(R.color.main_red));
        }

        /**
         * 计时过程显示
         *
         * @param millisUntilFinished
         */
        @Override
        public void onTick(long millisUntilFinished) {
            isTimeCount = true;
//            tv_auth_code.setClickable(false);
            tv_auth_code.setTextColor(getResources().getColor(R.color.gray));
            tv_auth_code.setText(millisUntilFinished / 1000 + "秒后重试");
        }
    }

    /**
     * 验证码输入监听
     */
    private TextWatcher authCodeEdit = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//            Log.i("123", "phoneNumberEdit-start:" + start + before);
            if ((start == 5) && isComplete && (before == 0)) {
                bt_next.setBackgroundResource(R.drawable.btn_common_selector);
//                bt_next.setClickable(true);
            } else if ((start == 5) && (before == 0)) {//正向输入
                isComplete = true;
            } else {
                bt_next.setBackgroundResource(R.drawable.btn_disable_selector);
//                bt_next.setClickable(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    /**
     * 手机号输入监听
     */
    private TextWatcher phoneNumberEdit = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//            Log.i("123", "phoneNumberEdit-start:" + start + before);
            if ((start == 10) && isComplete && (before == 0)) {
                bt_next.setBackgroundResource(R.drawable.btn_common_selector);
//                bt_next.setClickable(true);
            } else if ((start == 10) && (before == 0)) {// 正向输入
                isComplete = true;
            } else {
                bt_next.setBackgroundResource(R.drawable.btn_disable_selector);
//                bt_next.setClickable(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    /**
     * 密码输入监听
     */
    private TextWatcher passwordEdit = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//            Log.i("123", "phoneNumberEdit-start:" + start + before);
            if (et_password.length() >= 6 && et_passwordOk.length() >= 6) {
                isComplete = true;
            } else {
                isComplete = false;
            }
            if (isComplete) {
                bt_ok.setBackgroundResource(R.drawable.btn_common_selector);
//                bt_ok.setClickable(true);
            } else {
                bt_ok.setBackgroundResource(R.drawable.btn_disable_selector);
//                bt_ok.setClickable(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };
}
